<?php


namespace app\model;

use app\process\CalFeature;
use fast\Http;
use think\facade\Cache;
use think\facade\Log;
use think\Model;

class AlbumPhoto extends Model {

    public static function comparePhoto($feature,$log_id) {
        Log::info($log_id.'对比地库');
        //$lists=self::whereNotNull('feature')->select();
        $lists=AlbumFeature::select();
        $_calFeature=new CalFeature();
        $config=config('capture.Local');
        $score=$config['max_feture'];
        foreach ($lists as $list) {
            $cal_res=$_calFeature->compare_feature_str($feature,$list['feature']);
            if($cal_res>$score){
                return $list;
            }
        }
        return null;
    }

    /**
     * 对album_photo表中feature_status=0的特征值进行计算，然后与album_feature表中的数据进行对比，如果比中则归档，未比中则创建新数据
     * @return void
     */
    public function get_album_photo_feature($id) {
        $now_time=date("Y-m-d H:i:s");
        $log_id=md5($now_time).rand(1000,9999);
        Log::info($log_id.'底库特征值计算:'.$id);
        $key="is_album_photo_caling";
        $caling=Cache::get($key);
        if($caling&&(time()-$caling<120)){
            Log::info($log_id.'底库特征值计算中，返回');
            return;
        }
        Cache::set($key,time());
        $where[]=['feature_status','=',0];
        if($id){
            $where[]=['id','=',$id];
        }
        $lists=$this->where($where)->limit(20)->select();
        $_calFeature=new CalFeature();
        $_face=new Faces();
        $_feature=new Feature();
        Log::info($log_id.'获取photo列表:'.json_encode($lists));
        $_album_people=new AlbumPeople();
        foreach ($lists as $list) {
            try {
                if(!file_exists($list['file_path'].$list['id'].'.jpg')){
                    $list->feature_status=-2;
                    $list->feature_fail='图片丢失';
                }else{
                    $feature=$_calFeature->get_feature($list['file_path'].$list['id'].'.jpg',$log_id);
                    Log::info($log_id.'获取feature:'.$feature);
                    if($feature){
                        //获取featur后，首先比较底库，如果底库存在，则归档人员，如果不存在，创建新记录
                        $results=$_feature->compare_feature($feature,'album',config('capture.Local.max_feture'),$log_id);
                        Log::info($log_id.'获取比对结果:'.json_encode($results));
                        //$results=false;
                        if($results){
                            //得分最高的，设置为people_id，其余的people进行归档
                            for ($i=0 ;$i < count($results);$i++){
                                if($i===0){
                                    Log::info($log_id.'获取people_id:'.$results[$i]['id']);
                                    $list->people_id=$results[$i]['id'];
                                    $old_people=AlbumPeople::find($results[$i]['id']);
                                    if(!$old_people->album_id){
                                        $old_people->album_id=$list['album_id'];
                                        $old_people->name=$list['name'];
                                        $old_people->idcard=$list->idcard;
                                        $old_people->address=$list->address;
                                        $old_people->contact_name=$list->contact_name;
                                        $old_people->contact_tel=$list->contact_tel;
                                        $old_people->file_path=$list->file_path.$list->id.'.jpg';
                                        //$_album_people->where('id',$old_people['id'])->save((array)$old_people);
                                        $old_people->save();
                                    }
                                }else{

                                }
                            }
                            /*$change=false;
                            foreach ($results as $result) {
                                if($result['id']<$list['id']){
                                    //在底库找到
                                    $_album_people->where(['photo_id'=>$list['id']])->save(['photo_id'=>$result['id']]);
                                    $list->delete();
                                    $change=true;
                                    break;
                                }
                            }
                            if($change){
                                continue;
                            }*/
                        }else{
                            Log::info($log_id.'没有比中:');
                            $people['name']=$list['name'];
                            $people['album_id']=$list['album_id'];
                            $people['idcard']=$list->idcard;
                            $people['address']=$list->address;
                            $people['contact_name']=$list->contact_name;
                            $people['contact_tel']=$list->contact_tel;
                            $people['file_path']=$list->file_path.$list->id.'.jpg';
                            $people['create_at']=$list->create_at;
                            $people['show_num']=0;
                            //Log::error('xxxx:'.json_encode($people));
                            $peoples=AlbumPeople::create((array)$people);
                            $data['id']=$peoples->id;
                            $data['feature']=$feature;
                            AlbumFeature::create($data);
                            $list->people_id=$data['id'];
                        }
                        //$list->feature=$feature;
                        $list->feature_status=1;
                    }else{
                        $list->feature_status=2;
                    }
                }

                //比较face表历史数据
                /*$_face->compare_all_by_ablum_photo($feature,$list->id,$log_id);
                sleep(60);
                $count=$_face->where('photo_id',$list->id)->count();
                if($count){
                    $last_time=$_face->where('photo_id',$list->id)->max('create_time');
                    $list->last_time=$last_time;
                }
                $list->show_num=$count;
                */
                $list->save();
            }catch (\Exception $e){
                Log::error("获取底库特征值错误:".$e->getMessage());
                $list->feature_status=2;
                $list->save();
            }
        }
        Cache::delete($key);
        Log::info($log_id.'底库特征值计算结束');
    }

    /**
     * 和战法底库进行比较，返回单条album_photo的值，增加score字段,增加is_all字段，可以返回全部数据
     * @param $feature
     * @param $log_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function compare_face_feature($feature,$log_id,$is_all=false) {
        Log::info($log_id."和底库进行比较，获取最大值");
        $logic=config('capture.logic');
        if($logic){
            $_feature=new Feature();
            $res=$_feature->compare_feature($feature,'album',config('capture.Local.max_feture'),$log_id);
            if($res&&!$is_all){
                $res=$res[0];
            }
        }else{
            $_face=new Faces();
            $all=$this->where('feature_status',1)->select()->toArray();
            $res=$_face->cal_max_feature($all,$feature,$log_id);
        }
        Log::debug($log_id."获取底库最大值：".json_encode($res));
        return $res;
        /*if($res){
            return $res['id'];
        }else{
            return '';
        }*/
    }


    public function create_data($people_id,$path)  {
        $now=date("Y-m-d H:i:s");
        $config=config('capture.Local');
        $data['album_id']=-1;
        $data['people_id']=$people_id;
        $data['feature_status']=1;
        $data['create_at']=$now;
        $data['last_time']=$now;
        $data['source_type']=1;
        $data['show_num']=1;
        $file_path=$config['capture_path'].'/album/-1/'.date('Ym').'/'.date('d').'/';
        $data['file_path']=$file_path;
        $this->save($data);
        save_base_img($this->id,base64_img($path,0),$file_path);
        /*$photo_feature['id']=$this->id;
        $photo_feature['feature']=$feature;
        $_photo_feature=new AlbumFeature();
        $_photo_feature->save($photo_feature);*/
        return $this->id;
    }
}